<?php


namespace app\admin\controller\auth;


use app\admin\controller\AController;
use app\admin\service\auth\AdminRuleService;
use app\admin\service\RequestService;
use app\model\auth\AdminGroup;
use app\model\auth\AdminRule;
use think\Request;

class AdminGroupController extends AController {

    public function index(RequestService $requestService): \think\response\Json
    {
        $list = $requestService->read(new AdminGroup());
        return jsonSuccess([
            'items' => $list->items(),
            'total' => $list->total(),
        ]);
    }

    public function add(Request $request, RequestService $requestService){
        return $requestService->add(new AdminGroup());
    }

    public function edit(Request$request, RequestService  $requestService): \think\response\Json
    {
        if ($request->isPost()){
            return $requestService->edit(new AdminGroup());
        }else{
            $id = $request->param('id');
            $info = AdminGroup::find($id);
            if (!$info) return jsonError(NOT_FOUND);
            return jsonSuccess([
                'info' => $info
            ]);
        }
    }

    public function rule(Request $request): \think\response\Json
    {
        $groupId = $request->param('group_id');
        if($request->isPost()){

            $rules = $request->param('rules');
            $rules = miImplode($rules);
            return (new RequestService())->edit(new AdminGroup(), data: [
                'id' => $groupId,
                'rules' => $rules,
            ]);

        }else{

            if(!$groupId) return jsonError('没有数据');
            // 获得所有权限
            $rules = AdminRule::field(['id', 'title', 'pid', 'sort'])->where('status', 1)->order('sort desc')->select();
            $trees = (new AdminRuleService())->childrenTree($rules);
            $checked = AdminGroup::where('id', $groupId)->value('rules');
            $checked = miExplode($checked);

            return jsonSuccess([
                'trees' => $trees,
                'checked' => $checked,
            ]);

        }
    }

    public function del(Request $request, RequestService $requestService){
        return $requestService->del(new AdminGroup());
    }


    public function options(){
        $options = AdminGroup::field('id,title')->where('status',1)->select();
        return jsonSuccess([
            'options' => $options,
        ]);
    }


}
